package com.yichen.rent.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yichen.rent.utils.MultipartFileToFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zhangchenbin
 * @date 2020-03-15
 * @description
 */
@Slf4j
@RestController
public class UploadController {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.firstKey}")
    private String firstKey;


    @PostMapping("/upload")
    public Map<String, Object> ossUpload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Map<String, Object> map = new HashMap<>();
        try {

            if (ossClient.doesBucketExist(bucketName)) {
                System.out.println("您已经创建Bucket：" + bucketName + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + bucketName + "。");
                ossClient.createBucket(bucketName);
            }

            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String fileKey = System.currentTimeMillis() + suffixName;

            ossClient.putObject(bucketName, fileKey, MultipartFileToFile.multipartFileToFile(file));
            System.out.println("Object：" + fileKey + "存入OSS成功。");
            map.put("code", 1);
            map.put("msg", "上传成功");

            map.put("src", fileKey);

            return map;

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "上传失败");
            return map;
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 删除图片
     *
     * @return
     */
    @DeleteMapping("/remove")
    public Map<String, Object> ossUploadRemove(String fileKey) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Map<String, Object> map = new HashMap<>();
        try {

            if (ossClient.doesBucketExist(bucketName)) {
                System.out.println("您已经创建Bucket：" + bucketName + "。");
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + bucketName + "。");
                ossClient.createBucket(bucketName);
            }

            ossClient.deleteObject(bucketName, fileKey);
            System.out.println("删除Object：" + fileKey + "成功。");
            map.put("code", 1);
            map.put("msg", "删除成功");
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "删除失败");
            return map;
        } finally {
            ossClient.shutdown();
        }
    }

    @Value("${filePath}")
    private String filePath;

    //@PostMapping("/upload")
    public Map<String, Object> upload(MultipartFile file) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String utf8 = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        String staticPath = URLDecoder.decode(utf8, "utf8");
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        //String filePath =staticPath+ "/upload/"; // 上传后的路径
        System.out.println(filePath);
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            map.put("code", 1);
            map.put("msg", "上传成功");

            map.put("src", fileName);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "上传失败");
            return map;
        }
    }
}
